package prj.carmap.mobile.activity;


import prj.carmap.mobile.CarmapApplication;
import prj.carmap.mobile.R;
import prj.carmap.mobile.process.BMapGeneralListener;
import prj.carmap.mobile.view.ZoomControlView;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Window;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.RouteOverlay;
import com.baidu.mapapi.map.TransitOverlay;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviPara;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPlanNode;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKRoute;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKShareUrlResult;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;

/**
 * 线路规划界面
 * 百度地图显示到目的地路线
 *
 */
public class RoutePlanActivity extends SherlockActivity {

	final static String TAG = "RoutePlanActivity";

	//UI相关
	Button mBtnDrive = null; // 驾车搜索
	Button mBtnTransit = null; // 公交搜索
	Button mBtnWalk = null; // 步行搜索
	Button mBtnCusRoute = null; //自定义路线
	Button mBtnCusIcon = null; //自定义起终点图标

	private ZoomControlView mZoomControlView;
	
	//浏览路线节点相关
	Button mBtnPre = null;//上一个节点
	Button mBtnNext = null;//下一个节点
	int nodeIndex = -2;//节点索引,供浏览节点时使用
	MKRoute route = null;//保存驾车/步行路线数据的变量，供浏览节点时使用
	TransitOverlay transitOverlay = null;//保存公交路线图层数据的变量，供浏览节点时使用
	RouteOverlay routeOverlay = null;
	boolean useDefaultIcon = false;
	int searchType = -1;//记录搜索的类型，区分驾车/步行和公交
	//private PopupOverlay pop = null;//弹出泡泡图层，浏览节点时使用
	//private TextView popupText = null;//泡泡view
	//private View viewCache = null;
	private BMapManager bMapManager;

	//地图相关，使用继承MapView的MyRouteMapView目的是重写touch事件实现泡泡处理
	//如果不处理touch事件，则无需继承，直接使用MapView即可
	MapView mMapView = null; // 地图View
	//搜索相关
	MKSearch mSearch = null; // 搜索模块，也可去掉地图模块独立使用

	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
		super.onCreate(savedInstanceState);

		Log.d(TAG, "onCreate");
		CarmapApplication.currentPage = "";
		CarmapApplication.addActivity(this);

		/**
		 * 使用地图sdk前需先初始化BMapManager. BMapManager是全局的，可为多个MapView共用，它需要地图模块创建前创建，
		 * 并在地图地图模块销毁后销毁，只要还有地图模块在使用，BMapManager就不应该销毁
		 */
		if (bMapManager == null)
		{
			bMapManager = new BMapManager(getApplicationContext());
			//如果BMapManager没有初始化则初始化BMapManager
			bMapManager.init(CarmapApplication.strKey, new BMapGeneralListener(CarmapApplication.getInstance()));
		}

		//由于MapView在setContentView()中初始化,所以它需要在BMapManager初始化之后
		setContentView(R.layout.activity_routeplan);

		// Inflate the custom view
		//View customNav = LayoutInflater.from(this).inflate(R.layout.nav_view, null);
		View customNav = LayoutInflater.from(this).inflate(R.layout.nav_routeplan_view, null);
		// Attach to the action bar
		getSupportActionBar().setCustomView(customNav);
		getSupportActionBar().setDisplayShowCustomEnabled(true);
		getSupportActionBar().setDisplayShowHomeEnabled(false);
		getSupportActionBar().setDisplayShowTitleEnabled(false);


		//导航条按钮监听
		//Button returnBtn = (Button) customNav.findViewById(R.id.return_prev);
		View returnBtn = customNav.findViewById(R.id.return_prev);
		TextView t = (TextView) customNav.findViewById(R.id.nav_title);
		t.setText("导航");
		t.setTextColor(Color.BLACK);
		returnBtn.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				RoutePlanActivity.this.finish();
			}
		});

		//Button mapnavBtn = (Button) customNav.findViewById(R.id.map_nav);
		View mapnavBtn = customNav.findViewById(R.id.map_nav);
		mapnavBtn.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				int startPosLat = getIntent().getIntExtra("startPosLat", 0);
				int startPosLng = getIntent().getIntExtra("startPosLng", 0);
				int endPosLat = getIntent().getIntExtra("endPosLat", 0);
				int endPosLng = getIntent().getIntExtra("endPosLng", 0);

				GeoPoint startPos = new GeoPoint(startPosLat, startPosLng);
				GeoPoint endPos = new GeoPoint(endPosLat, endPosLng);

				/**
				 * 导航参数
				 * 导航起点和终点不能为空，当GPS可用时启动从用户位置到终点间的导航，
				 * 当GPS不可用时，启动从起点到终点间的模拟导航。
				 */
				final NaviPara para = new NaviPara();
				para.startPoint = startPos; //起点坐标
				para.startName = "从这里开始";
				para.endPoint = endPos; //终点坐标
				para.endName = "到这里结束";
				try {
					//调起百度地图客户端导航功能,参数this为Activity。
					BaiduMapNavigation.openBaiduMapNavi(para, RoutePlanActivity.this);
				}
				catch (BaiduMapAppNotSupportNaviException e) {
					//在此处理异常
					e.printStackTrace();
					Log.e("" + e, "不支持导航功能");

					AlertDialog.Builder builder = new AlertDialog.Builder(RoutePlanActivity.this);
					builder.setMessage("您尚未安装百度地图App或App版本过低！");
					builder.setTitle("提示");

					builder.setNegativeButton("安装百度地图", new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							BaiduMapNavigation.GetLatestBaiduMapApp(RoutePlanActivity.this);
						}
					});

					builder.setNeutralButton("尝试Web导航", new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							//尝试调启Web页面的导航
							BaiduMapNavigation.openBaiduMapNavi(para, RoutePlanActivity.this);
						}
					});

					builder.setPositiveButton("取消", new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});

					builder.create().show();


					//Toast.makeText(CarmapApplication.getInstance().getApplicationContext(), "导航功能需要你的手机安装百度地图5.0以上版本！", Toast.LENGTH_LONG).show();

					//Toast.makeText(CarmapApplication.getInstance().getApplicationContext(), "下面将尝试调启Web页面的导航！", Toast.LENGTH_LONG).show();
					//尝试调启Web页面的导航
					//BaiduMapNavigation.openWebBaiduMapNavi(para, RoutePlanActivity.this);
				}
			}
		});


		//初始化地图
		mMapView = (MapView) findViewById(R.id.bmapRouteView);
		mMapView.setBuiltInZoomControls(false);
		mMapView.getController().setZoom(12);
		mMapView.getController().enableClick(false);
		mMapView.getController().setScrollGesturesEnabled(true);

		mZoomControlView = (ZoomControlView) findViewById(R.id.OverlayZoomControlView);
		mZoomControlView.setMapView(mMapView);
		
		// 初始化搜索模块，注册事件监听
		mSearch = new MKSearch();
		mSearch.init(bMapManager, new MKSearchListener() {

			public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) {
				// 错误号可参考MKEvent中的定义
				if (error != 0 || res == null) {
					Toast.makeText(RoutePlanActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
					return;
				}

				searchType = 0;
				routeOverlay = new RouteOverlay(RoutePlanActivity.this, mMapView);
				// 此处仅展示一个方案作为示例
				routeOverlay.setData(res.getPlan(0).getRoute(0));
				//清除其他图层
				mMapView.getOverlays().clear();
				//添加路线图层
				mMapView.getOverlays().add(routeOverlay);
				//执行刷新使生效
				mMapView.refresh();
				//使用zoomToSpan()绽放地图，使路线能完全显示在地图上
				mMapView.getController().zoomToSpan(routeOverlay.getLatSpanE6(), routeOverlay.getLonSpanE6());
				//移动地图到起点
				mMapView.getController().animateTo(res.getStart().pt);
				//将路线数据保存给全局变量
				route = res.getPlan(0).getRoute(0);
				//重置路线节点索引，节点浏览时使用
				nodeIndex = -1;
			}

			public void onGetTransitRouteResult(MKTransitRouteResult res, int error) {
			}

			public void onGetWalkingRouteResult(MKWalkingRouteResult res, int error) {
			}

			public void onGetAddrResult(MKAddrInfo res, int error) {
			}

			public void onGetPoiResult(MKPoiResult res, int arg1, int arg2) {
			}

			public void onGetBusDetailResult(MKBusLineResult result, int iError) {
			}

			@Override
			public void onGetSuggestionResult(MKSuggestionResult res, int arg1) {
			}

			@Override
			public void onGetPoiDetailSearchResult(int type, int iError) {
			}

			@Override
			public void onGetShareUrlResult(MKShareUrlResult result, int type, int error) {

			}
		});

		int startPosLat = getIntent().getIntExtra("startPosLat", 0);
		int startPosLng = getIntent().getIntExtra("startPosLng", 0);
		int endPosLat = getIntent().getIntExtra("endPosLat", 0);
		int endPosLng = getIntent().getIntExtra("endPosLng", 0);

		GeoPoint startPos = new GeoPoint(startPosLat, startPosLng);
		GeoPoint endPos = new GeoPoint(endPosLat, endPosLng);
		// 对起点终点的name进行赋值，也可以直接对坐标赋值，赋值坐标则将根据坐标进行搜索
		MKPlanNode stNode = new MKPlanNode();
		stNode.pt = startPos;
		MKPlanNode enNode = new MKPlanNode();
		enNode.pt = endPos;
		// 设置驾车路线搜索策略，时间优先、费用最少或距离最短
		mSearch.setDrivingPolicy(MKSearch.ECAR_TIME_FIRST);
		mSearch.drivingSearch("中国", stNode, "中国", enNode);
	}

	@Override
	protected void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		mMapView.destroy();
//		mSearch.destory();
		mSearch = null;
		super.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mMapView.onRestoreInstanceState(savedInstanceState);
	}

}
